# Makefile for MPI Performance Diagnostic Tool
# 适用于鲲鹏服务器

# 编译器选择
# 自动检测MPI编译器
MPICXX := $(shell which mpicxx 2>/dev/null || which mpiCC 2>/dev/null || which mpic++ 2>/dev/null)

ifeq ($(MPICXX),)
    $(error MPI C++ compiler not found! Please install OpenMPI or MPICH)
endif

# 程序名称
TARGET = mpiTest
SOURCE = mpiTest.cpp

# 编译选项

# 基础优化选项
CXXFLAGS = -O3 -std=c++11 -fopenmp -Wall -Wextra

# 架构优化（针对鲲鹏920）
# 如果是鲲鹏，使用armv8.2-a优化
ARCH := $(shell uname -m)
ifeq ($(ARCH),aarch64)
    # 鲲鹏920特定优化
    CXXFLAGS += -march=armv8.2-a -mtune=tsv110
    $(info Building for Kunpeng 920 (aarch64))
else ifeq ($(ARCH),x86_64)
    # x86架构优化
    CXXFLAGS += -march=native -mtune=native
    $(info Building for x86_64)
else
    # 通用优化
    CXXFLAGS += -march=native
    $(info Building for $(ARCH))
endif

# 链接库
LDFLAGS = -lm

# 编译目标
.PHONY: all clean help test

all: $(TARGET)

$(TARGET): $(SOURCE)
	@echo "========================================"
	@echo "  Compiling MPI Performance Tool"
	@echo "========================================"
	@echo "Compiler: $(MPICXX)"
	@echo "Flags: $(CXXFLAGS)"
	@echo "Architecture: $(ARCH)"
	@echo ""
	$(MPICXX) $(CXXFLAGS) -o $(TARGET) $(SOURCE) $(LDFLAGS)
	@echo ""
	@echo "========================================"
	@echo "  Build Successful!"
	@echo "========================================"
	@echo "Executable: ./$(TARGET)"
	@echo ""
	@echo "Usage:"
	@echo "  mpirun -np <N> ./$(TARGET)"
	@echo ""

# 清理
clean:
	@echo "Cleaning up..."
	rm -f $(TARGET) *.o
	@echo "Done."

# 测试（快速验证）
test: $(TARGET)
	@echo "Running quick test with 4 processes..."
	mpirun -np 4 ./$(TARGET)

# 优化版本（激进优化，可能不够稳定）
aggressive: CXXFLAGS += -Ofast -ffast-math -flto
aggressive: clean all

# 调试版本
debug: CXXFLAGS = -O0 -g -std=c++11 -fopenmp -Wall -Wextra
debug: clean all

# 帮助信息
help:
	@echo "MPI Performance Diagnostic Tool - Makefile"
	@echo ""
	@echo "Targets:"
	@echo "  make              - Compile the program (default)"
	@echo "  make all          - Same as make"
	@echo "  make clean        - Remove compiled files"
	@echo "  make test         - Compile and run quick test (4 processes)"
	@echo "  make aggressive   - Compile with aggressive optimizations"
	@echo "  make debug        - Compile with debug symbols"
	@echo "  make help         - Show this help message"
	@echo ""
	@echo "Examples:"
	@echo "  make                    # Standard compilation"
	@echo "  make test               # Compile and quick test"
	@echo "  make MPICXX=mpiCC       # Use specific MPI compiler"
	@echo ""
	@echo "After compilation:"
	@echo "  mpirun -np <N> ./$(TARGET)"
	@echo "  ./run_mpi_scaling_test.sh"
	@echo ""

